package com.zz.util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

/**
 * @author zhr
 */
public class Base64Util {
    private static final String _CHARSET = "UTF-8";

    public static String encode(String content) {
        try {
            return new String(Base64.getEncoder().encode(content.getBytes(_CHARSET)), _CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    public static String encode(byte[] content) {
        try {
            return new String(Base64.getEncoder().encode(content), _CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    public static String decode(String content) {
        try {
            return new String(Base64.getDecoder().decode(content.getBytes(_CHARSET)), _CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    public static String encodeUrl(String content) {
        try {
            return new String(Base64.getUrlEncoder().encode(content.getBytes(_CHARSET)), _CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    public static String decodeUrl(String content) {
        try {
            return new String(Base64.getUrlDecoder().decode(content.getBytes(_CHARSET)), _CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws IOException {
        System.out.println(encode("哈哈"));
        System.out.println(decode(encode("哈哈")));
        System.out.println(encodeUrl("历史上的今天- 维基百科，自由的百科全书"));
        System.out.println(decodeUrl(encodeUrl("历史上的今天- 维基百科，自由的百科全书")));
        System.out.println(decodeUrl("5Y6G5Y-y5LiK55qE5LuK5aSpLSDnu7Tln7rnmb7np5HvvIzoh6rnlLHnmoTnmb7np5HlhajkuaY"));

//        System.out.println(encode(FileUtils.readFileToByteArray(new File("D:/var/base/t.png"))));
//        FileUtils.write(new File("D:/var/base/t.txt"), encode(FileUtils.readFileToByteArray(new File("D:/var/base/t.png"))), "utf-8");

        System.out.println(decodeUrl("GGc1Xc-WBcygswX8oYCgCg"));
        System.out.println(decode("QUFodHRwOi8vZG93bi5zYW5kYWkubmV0L3RodW5kZXI3L1RodW5kZXI3LjEuNS4yMTUyLmV4ZVpa"));


        System.out.println(FileUtils.checksum(new File("D:/var/base/t.txt"), new CRC32()).getValue());
        System.out.println(FileUtils.checksumCRC32(new File("D:/var/base/t.txt")));
    }

}
